<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>数组find和findIndex方法</title>
</head>

<body>
  <script>
    // ============================== 数组find和findIndex方法 ==============================
    const goods = [
      {
        name: '小米',
        price: 1999
      },
      {
        name: '华为',
        price: 4999
      },
      {
        name: '苹果',
        price: 9999
      }
    ]

    // 1. find  查找满足条件的元素，返回第一个满足条件的元素，找不到则返回undefined
    //    需求：找出 >= 2000 的结果
    const total = goods.find(ele => ele.price >= 2000)
      console.log(total) //查找满足条件的元素，第一项
      const total2 = goods.find(ele => ele.price >= 20000)
      console.log(total2) //查找不到输出undefined
      

    // 1.1 和 filter的区别
    // (1) 返回值不一样， filter 返回的是数组  find 返回的是数组元素
    // (2) 查找方式不一样，filter是查找所有满足条件的数组元素， find只查找第一个满足条件的，找到就终止查  
    
    const res = goods.filter(ele => ele.price>=2000)
    console.log(res)//[{name: '华为', price: 4999} ,{name: '苹果', price: 9999}]
    
    // 2. findIndex 查找满足条件的元素的索引号，找不到则返回-1
    const res1 = goods.findIndex(ele => ele.price >= 2000)
    console.log(res1)  //1
    const res2 = goods.findIndex(ele => ele.price >= 20000)
    console.log(res2)  //-1

  </script>
</body>

</html>